package com.example.config;


import com.example.security.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * 对Security核心配置进行一层配置
 */

@Configuration
@EnableWebSecurity               //加载Security相关的安全策略的配置
@EnableGlobalMethodSecurity(prePostEnabled = true)      //post请求前都要进行权限的校验
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    LoginFailureHandler loginFailureHandler;            //引入登录失败处理器

    @Autowired
    LoginSuccessHandler loginSuccessHandler;             //引入登录成功处理器

    @Autowired
    CaptchaFilter captchaFilter;                         //引入验证码过滤器

    @Autowired
    JwtAccessDeniedHandler jwtAccessDeniedHandler;      //引入权限不足处理器

    @Autowired
    JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;  //引入认证失败处理器

    @Autowired
    UserDetailsServiceImpl userDetailsService;              //引入用户登录查库处理

    @Autowired
    JwtLogoutSuccessHandler jwtLogoutSuccessHandler;        //引入用户退出处理


    @Bean
    JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {     //引入自定义Jwt认证过滤器
        JwtAuthenticationFilter jwtAuthenticationFilter = new JwtAuthenticationFilter(authenticationManager());
        return jwtAuthenticationFilter;
    }

    //配置密码的加密形式
    @Bean
    BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    //静态资源拦截白名单
    private static final String[] URL_WHITELIST = {
            "/login",
            "/logout",
            "/captcha",
            "/favicon.ico",
    };


    //配置http相关安全的
    protected void configure(HttpSecurity http) throws Exception {

        //配置跨域的问题，运行跨域和关闭预防攻击
        http.cors().and().csrf().disable()

                //登录配置
        .formLogin()
                .successHandler(loginSuccessHandler)        //登录成功
                .failureHandler(loginFailureHandler)        //登录失败

        .and()
                .logout()
                .logoutSuccessHandler(jwtLogoutSuccessHandler)    //用户退出

                //禁用session
        .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

                //配置拦截规则
        .and()
                .authorizeRequests()
                .antMatchers(URL_WHITELIST).permitAll()
                .anyRequest().authenticated()

                //异常处理器
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)  //认证失败
                .accessDeniedHandler(jwtAccessDeniedHandler)            //权限不足


                //配置自定义的过滤器
        .and()
        .addFilter(jwtAuthenticationFilter())
        .addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class)     //配置验证码过滤器在登录处理过滤器之前
        ;
    }

    //把用户登录查库注入security中
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }
}
